from flask import Blueprint, jsonify, current_app, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.user_models import User, Friendship
from models.message_models import Message
from sqlalchemy import func, or_
import uuid
import logging

logger = logging.getLogger(__name__)

contacts_bp = Blueprint('contacts', __name__, url_prefix='/api')

@contacts_bp.route('/contacts', methods=['GET'])
@jwt_required()
def get_contacts():
    """获取用户的好友列表"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        # 只获取用户的好友
        friends = Friendship.get_friends(current_user_uuid)
        
        contacts = []
        for friend in friends:
            # 获取与这个好友的最后一条消息
            last_message = Message.query.filter(
                or_(
                    (Message.sender_id == current_user_uuid) & (Message.receiver_id == friend.id),
                    (Message.sender_id == friend.id) & (Message.receiver_id == current_user_uuid)
                )
            ).order_by(Message.timestamp.desc()).first()
            
            contact_data = {
                'id': str(friend.id),
                'username': friend.username,
                'public_key': friend.public_key,
                'online': friend.online,
                'lastMessage': {
                    'content': '[Encrypted]' if last_message else '',
                    'timestamp': last_message.timestamp.isoformat() if last_message else None,
                    'senderId': str(last_message.sender_id) if last_message else None
                }
            }
            contacts.append(contact_data)
        
        return jsonify(contacts), 200
    except Exception as e:
        logger.error(f"Error fetching contacts: {str(e)}")
        return jsonify({'error': 'Failed to fetch contacts'}), 500


@contacts_bp.route('/friend-requests', methods=['GET'])
@jwt_required()
def get_friend_requests():
    """获取用户的好友请求列表"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        # 获取发给当前用户的好友请求
        requests = Friendship.query.filter(
            (Friendship.friend_id == current_user_uuid) &
            (Friendship.status == 'pending')
        ).all()
        
        request_list = []
        for req in requests:
            user = User.query.get(req.user_id)
            if user:
                request_list.append({
                    'id': str(req.id),
                    'userId': str(user.id),
                    'username': user.username,
                    'online': user.online,
                    'requestedAt': req.created_at.isoformat()
                })
        
        return jsonify(request_list), 200
        
    except Exception as e:
        logger.error(f"Error fetching friend requests: {str(e)}")
        return jsonify({'error': 'Failed to fetch friend requests'}), 500


@contacts_bp.route('/friend-requests', methods=['POST'])
@jwt_required()
def send_friend_request():
    """发送好友请求"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        data = request.json
        friend_username = data.get('username')
        
        if not friend_username:
            return jsonify({'error': 'Username is required'}), 400
        
        # 查找目标用户
        friend_user = User.query.filter_by(username=friend_username).first()
        if not friend_user:
            return jsonify({'error': 'User not found'}), 404
        
        # 不能添加自己为好友
        if friend_user.id == current_user_uuid:
            return jsonify({'error': 'You cannot add yourself as a friend'}), 400
        
        # 检查是否已经是好友或已有请求
        existing = Friendship.query.filter(
            ((Friendship.user_id == current_user_uuid) & (Friendship.friend_id == friend_user.id)) |
            ((Friendship.user_id == friend_user.id) & (Friendship.friend_id == current_user_uuid))
        ).first()
        
        if existing:
            status = existing.status
            if status == 'accepted':
                return jsonify({'error': 'Already friends'}), 400
            elif status == 'pending':
                if existing.user_id == current_user_uuid:
                    return jsonify({'error': 'Friend request already sent'}), 400
                else:
                    return jsonify({'error': 'Friend request already received'}), 400
        
        # 创建好友请求
        friendship = Friendship.create_friend_request(current_user_uuid, friend_user.id)
        
        return jsonify({
            'id': str(friendship.id),
            'status': friendship.status,
            'friendId': str(friend_user.id),
            'friendUsername': friend_user.username
        }), 201
        
    except Exception as e:
        logger.error(f"Error sending friend request: {str(e)}")
        return jsonify({'error': 'Failed to send friend request'}), 500


@contacts_bp.route('/friend-requests/<request_id>/accept', methods=['POST'])
@jwt_required()
def accept_friend_request(request_id):
    """接受好友请求"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        # 查找好友请求
        friendship = Friendship.query.get(request_id)
        if not friendship:
            return jsonify({'error': 'Friend request not found'}), 404
        
        # 检查是否是发给当前用户的请求
        if friendship.friend_id != current_user_uuid:
            return jsonify({'error': 'Not authorized to accept this request'}), 403
        
        # 接受好友请求
        accepted = Friendship.accept_friend_request(current_user_uuid, friendship.user_id)
        if not accepted:
            return jsonify({'error': 'Failed to accept friend request'}), 400
        
        # 获取好友信息
        friend_user = User.query.get(friendship.user_id)
        
        return jsonify({
            'id': str(accepted.id),
            'status': accepted.status,
            'friendId': str(friend_user.id),
            'friendUsername': friend_user.username
        }), 200
        
    except Exception as e:
        logger.error(f"Error accepting friend request: {str(e)}")
        return jsonify({'error': 'Failed to accept friend request'}), 500


@contacts_bp.route('/friend-requests/<request_id>/reject', methods=['POST'])
@jwt_required()
def reject_friend_request(request_id):
    """拒绝好友请求"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        # 查找好友请求
        friendship = Friendship.query.get(request_id)
        if not friendship:
            return jsonify({'error': 'Friend request not found'}), 404
        
        # 检查是否是发给当前用户的请求
        if friendship.friend_id != current_user_uuid:
            return jsonify({'error': 'Not authorized to reject this request'}), 403
        
        # 删除好友请求
        db.session.delete(friendship)
        db.session.commit()
        
        return jsonify({'message': 'Friend request rejected'}), 200
        
    except Exception as e:
        logger.error(f"Error rejecting friend request: {str(e)}")
        return jsonify({'error': 'Failed to reject friend request'}), 500


@contacts_bp.route('/search-users', methods=['GET'])
@jwt_required()
def search_users():
    """搜索用户（用于添加好友）"""
    try:
        current_user_id = get_jwt_identity()
        current_user_uuid = uuid.UUID(current_user_id)
        
        # 获取搜索关键词
        query = request.args.get('q', '').strip()
        if not query:
            return jsonify([]), 200
        
        # 搜索用户（排除自己和已经是好友的用户）
        users = User.query.filter(
            User.id != current_user_uuid,
            User.username.ilike(f'%{query}%'),
            User.is_active == True
        ).all()
        
        # 过滤掉已经是好友或有好友请求的用户
        results = []
        for user in users:
            # 检查是否已经是好友或有好友请求
            existing = Friendship.query.filter(
                ((Friendship.user_id == current_user_uuid) & (Friendship.friend_id == user.id)) |
                ((Friendship.user_id == user.id) & (Friendship.friend_id == current_user_uuid))
            ).first()
            
            if not existing:
                results.append({
                    'id': str(user.id),
                    'username': user.username,
                    'online': user.online
                })
        
        return jsonify(results), 200
        
    except Exception as e:
        logger.error(f"Error searching users: {str(e)}")
        return jsonify({'error': 'Failed to search users'}), 500